#include <iostream>
#include <string>
#include <unistd.h>
#include "../Common/httplib.h"
#include "Control.hpp"
#include "Model.hpp"
#include "View.hpp"
#include "Daemon.hpp"
using namespace httplib;
using namespace ns_Control;
static const std::string default_source_path = "./wwwroot";

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: [./Process +  port]" << std::endl;
        exit(0);
    }
    Daemon(false,true);
    Server server;
    Control control;
    server.set_base_dir(default_source_path);
    //注册方法
    server.Get(R"(/all_questions)", [&control](const Request &req, Response &resp)
               { 
                    std::string html;
                    control.AllQuestions(&html);
                    resp.set_content(html,"text/html; charset=utf-8"); 
               });
    server.Post("/login",[&control](const Request &req, Response &resp)
               { 
                  std::string in;
                  control.Login(req.body,&in);
                  //2.获取session--id
                  resp.set_header("Location","/index.html");
                  resp.status = 302;
                   //3.设置cookie
                  resp.set_header("Set-Cookie",in);
               });
    server.Get(R"(/question/(\d+))", [&control](const Request &req, Response &resp)
               {
                    std::string number = req.matches[1];
                    std::string html;
                    control.OnceQuestion(number,&html);
                    resp.set_content(html,"text/html; charset=utf-8"); 
                });
    server.Post(R"(/judge/(\d+))", [&control](const Request &req, Response &resp)
               {
                    std::string number = req.matches[1];
                    std::string injson = req.body;
                    std::string outjson;
                    control.Judge(number,injson,&outjson);
                    resp.set_content(outjson,"application/json;charset=utf-8");
               });
    server.listen("0.0.0.0", atoi(argv[1]));
    return 0;
}

